<template>

  <a-layout>
    <a-layout-content
        :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
    >
      <p>
        <a-space size="large">
          <a-input v-model:value="queryValue" placeholder="Input category name" size="large"/>
          <a-button type="primary" size="large" @click="categorySearch({name: queryValue})">
            <template #icon><SearchOutlined /></template>
            Search
          </a-button>
          <a-button size="large" @click="handleQuery">
            Cancel Search
          </a-button>
          <a-button type="primary" @click="add" size="large">
            Create
          </a-button>
        </a-space>
      </p>
      <a-table
          :columns="columns"
          :row-key="record => record.id"
          :data-source="level1"
          :loading="loading"
          :pagination="false"
      >
        <!--点击分页时会执行handleTableChange方法-->
        <template #cover="{ text: cover }">
          <img v-if="cover" :src="cover" alt="avatar"/>
        </template>
        <template v-slot:action="{text, record}"> <!--record是按钮所对应的行的数据-->
          <a-space size="small"> <!-- <a-space> : 空格组件，两个按钮要用空格隔开-->
            <a-button type="primary" @click="edit(record)">
              Edit
            </a-button>
            <a-popconfirm
                title="Are you sure delete this category?"
                ok-text="Yes"
                cancel-text="No"
                @confirm="confirm(record.id)"

            >
              <a-button type="danger">
                Delete
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-layout-content>
  </a-layout>
  <a-modal
      v-model:visible="modalVisible"
      title="分类表单"
      :confirm-loading="modalConfirmLoading"
      @ok="modalHandleOk"
  >
    <a-form :model="category" :label-col="{span : 6}" :wrapper-col="{ span: 18 }">
      <a-form-item label="名称">
        <a-input v-model:value="category.name"/>
      </a-form-item>
      <a-form-item label="顺序">
        <a-input v-model:value="category.sort"/>
      </a-form-item>
      <a-form-item label="父分类">
        <a-space>
          <a-select
              ref="select"
              v-model:value="category.parent"
              style="width: 355px"
          >
            <a-select-option value="0">无</a-select-option>
            <a-select-option v-for="c in level1" :key="c.id" :value="c.id" :disabled="category.id === c.id">{{c.name}}</a-select-option>
          </a-select>
        </a-space>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts">
import {defineComponent, onMounted, ref} from "vue";
import { message } from 'ant-design-vue';
import axios from "axios";
import { SearchOutlined } from '@ant-design/icons-vue';
import {Tool} from "@/util/tool"

export default defineComponent({
  components:{
    SearchOutlined,
  },
  name: 'AdminCategory',
  setup() {
    const queryValue = ref<string>(''); // 搜索框内容
    const categorys = ref();
    const category = ref();
    const loading = ref(false);
    const level1 = ref();
    level1.value = [];
    /**
     * level1一级分类树，children是二级分类
     * [
     *  id: " ",
     *  name: " ",
     *  children: [{
     *    id: " ",
     *    name: " ",
     *  }]
     *
     * ]
     *
     *
     * */
    const columns = [
      {
        title: '名称',
        dataIndex: 'name'
      },
      {
        title: '父分类',
        key: 'parent',
        dataIndex: 'parent',
      },
      {
        title: '顺序',
        key: 'sort',
        dataIndex: 'sort',
      },
      {
        title: 'Action',
        key: 'action',
        slots: {customRender: 'action'}
      }
    ];
    // const modalText = ref<string>('Content of the modal');

    /*
    * 查询相关函数
    *
    */
    // const categoryQuery = (queryValue: string) =>{
    //     axios.get("/category/list", {
    //       params:{
    //         name : queryValue
    //       }
    //     }).then((response) => {
    //       const data = response.data;
    //       if (data.success) {
    //         categorys.value = data.list; // categorys的数据在content下面的list中
    //
    //         // 重置分页按钮
    //         pagination.value.current = 1;
    //         pagination.value.total = data.content.total;
    //       }
    //     })
    // }

    /**
     * 删除相关函数
     */
    const confirm = (id : number) => {
      // console.log(e);
      // category.value = record;
      axios.delete("/category/delete/" + id).then((response) => {
        const data = response.data;
        if (data.success) { // data 等于 CommonResp
          message.success('Deleted Successfully');
          // 重新加载列表
          handleQuery();
        }
      })
    };



    // const cancel = (e : MouseEvent) => {
    //    console.log(e);
    //   message.error('You canceled this deletion');
    // };

    /**
     * 增加相关函数
    */
    const add = () =>{
      modalVisible.value = true;
      category.value = {};
    };
    /**
     * 编辑按钮相关
     */
    const modalVisible = ref(false);
    const modalConfirmLoading = ref(false);

    const edit = (record : any) => {
      modalVisible.value = true;
      category.value = Tool.copy(record);
    };

    const modalHandleOk = () => {
      // modalText.value = 'The modal will be closed after two seconds';
      modalConfirmLoading.value = true;

        axios.post("/category/save", category.value).then((response) => {
          modalConfirmLoading.value = false;
          const data = response.data;
          if (data.success) { // data 等于 CommonResp
            modalVisible.value = false;
            // 重新加载列表
            handleQuery();
          }
          else {
            message.error(data.message);
          }
        })
    };
    /**
     * 数据查询
     */
    const handleQuery = () => { // params:传递给后端的值。
      loading.value = true;
      level1.value = [];
      axios.get("/category/all").then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          categorys.value = data.content; // categorys的数据在content下面的list中
          console.log("原始数组：", categorys);
          level1.value = [];
          level1.value = Tool.array2Tree(categorys.value, 0);
          console.log("树形结构：", level1);
        }
        else {
          message.error(data.message);
        }
      })
    }

    const categorySearch = (params: any) => {
      loading.value = true;
      axios.get("/category/search",{
        params:{
          name: params.name
        }
      }).then((response) => {
        loading.value = false;
        const data = response.data;
        if (data.success) {
          categorys.value = data.content;
        }
        else {
          message.error(data.message);
        }
      })
    }

    /**
     * 表格点击页码时触发
     */
    // const handleTableChange = (pagination: any) => {
    //   console.log("看看自带的分页参数都有什么：" + pagination);
    //   handleQuery({
    //   });
    // }

    // 初始的时候会先执行onMounted方法
    onMounted(() => {
      handleQuery();
    });
    return {
      // categorys,
      level1,
      // pagination,
      columns,
      loading,
      // handleTableChange,

      modalVisible,
      modalConfirmLoading,
      modalHandleOk,
      edit,

      category,

      add,

      confirm,
      // cancel,
      queryValue,
      handleQuery,
      categorySearch,

    }
  }
})

</script>

<style>
img {
  width: 50px;
  height: 50px;
}
</style>

